﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QtConcurrent>
#include <QFuture>
#include <QScreen>
#include <QSound>
#include <QDir>
#include <QUuid>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_configDialog(new ConfigureDialog(this))
    , m_infoDialog(new SoftInfoDialog(this))
{
    ui->setupUi(this);
    this->setWindowIcon(QIcon(":/Image/Tag"));
    sysInit();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_action_open_triggered()
{

    if(m_seriesData.count()>0)
    {
        m_myChart->removeSeries();
    }

    auto srcDirPath = QFileDialog::getOpenFileName(
                this, tr("选择文件"), tr("/"),tr("CSV files(*.csv);;All files(*.*)")
                );

    if(srcDirPath.isEmpty())
    {
        return;
    }else{

        qDebug()<<"srcDirPath = "<<srcDirPath;
        auto tempGroup = srcDirPath.split("/");
        m_originFileName = tempGroup.last().split(".").first();
        qDebug()<<"file name is "<<m_originFileName;
        if(srcDirPath.endsWith("csv"))
        {
            m_seriesData.clear();
            qDebug()<<"pass";
            QVector<QStringList> originData = getSeriesData(srcDirPath);
            QFuture<QVector<QStringList>> future = QtConcurrent::run(this,&MainWindow::getSeriesData,srcDirPath);

            m_seriesData = future.result();

            qDebug()<<"m_seriesData get";

            m_myChart = new CustomZoomChart();

            m_myChart->setChartConfig(m_config);

            if(m_myChart->setChartView(m_seriesData))
            {
                this->setCentralWidget(m_myChart);
                if(m_config.displayResolution != "Auto Fit")
                {
                    qDebug()<<"fix resolution";
                    qDebug()<<m_config.displayResolution;
                    auto resolution = m_config.displayResolution.split("*");
                    auto width = resolution.at(0).toInt();
                    auto height = resolution.at(1).toInt();
                    this->resize(width,height);

                }else{

                    QScreen *screen = QGuiApplication::primaryScreen();
                    QRect mscreen = screen->availableGeometry();
                    int sc_width = mscreen.width();
                    int sc_height = mscreen.height();

                    qDebug()<<"current screen is w * h "<<sc_width<<"*"<<sc_height;

                    this->resize(sc_width,sc_height);

                }
                m_myChart->connectMarkers();
            }


            if(judgeSeriesData())
            {
                //"to do convert to series"

            }else{

                QMessageBox::warning(this,tr("数据错误"),tr("请检查输入数据是否为曲线数据！"));
            }


        }else{

            QMessageBox::warning(this,tr("警告"),tr("所选文件不是CSV文件！！"));
        }
    }

}

void MainWindow::sysInit()
{

    m_seriesData.clear();
    m_myChart = new CustomZoomChart();
    this->setCentralWidget(m_myChart);
    this->resize(800,600);

    connect(m_configDialog,&ConfigureDialog::configureFinish, this, &MainWindow::receiveConfigure);

    QString tag1 = "Resolution";
    if(m_chartConfigFile.GetConfig(tag1).isNull())
    {
        qDebug()<<"Init";
        m_chartConfigFile.chartConfigInit();

        auto targetDir = QDir::currentPath();

        targetDir += "/screenShot";
        qDebug()<<"creat path "<<targetDir<<endl;

        QDir srdir(targetDir);

        if(!srdir.exists())
        {
            if(srdir.mkdir(targetDir))
            {
                qDebug()<<"create successful!";
                QVariant path;
                QString tag2 = "ScreenShootPath";
                path = targetDir;
                m_chartConfigFile.setConfig(tag2,path);
                m_config.screenShotPath = path.toString();

            }else{

                qDebug()<<"create fail";
                QMessageBox::warning(this,tr("截屏路径创建失败"),tr("请检查软件权限（提升为管理员权限）！"));


            }
        }else{


            qDebug()<<"dir exists";
            QMessageBox::warning(this, tr("已存在截屏路径"),tr("请重启系统!"));
        }


    }

    this->getConfig();




    m_configDialog->setConfigure(m_config);


}


QVector<QStringList> MainWindow::getSeriesData(QString &filePath)
{
    QVector<QStringList> result;
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << file.errorString();
        return result;
    }

    QStringList wordList;
    QStringList resultList;
    while (!file.atEnd()) {

        QString line = file.readLine();
        wordList = line.split(',');
        resultList.clear();
        for(auto &item : wordList)
        {
            item = item.remove("\"");
            item = item.remove("\r\n");
            resultList.append(item);

        }
        result.append(resultList);
    }

   file.close();

   return result;


}

bool MainWindow::judgeSeriesData()
{
    if(m_seriesData.isEmpty())
    {
        return false;
    }else{

        auto firstData = m_seriesData[0];
        if(firstData.first() == "Date" && firstData[1] == "Time")
        {
            return true;
        }else{

            return false;
        }
    }

}

void MainWindow::getConfig()
{

    QString tag1 = "Theme",tag2 = "OpenGl", tag3 = "Resolution", tag4 = "MaxTip", tag5 = "MaxXaxis", tag6 = "MaxYaxis", tag7 = "ScreenShootPath";
    m_config.chartTheme = QChart::ChartTheme(m_chartConfigFile.GetConfig(tag1).toInt());
    m_config.enableOpenGL = m_chartConfigFile.GetConfig(tag2).toBool();
    m_config.maxTipPoints = m_chartConfigFile.GetConfig(tag4).toInt();
    m_config.displayResolution = m_chartConfigFile.GetConfig(tag3).toString();
    m_config.xAixsTickPoints = m_chartConfigFile.GetConfig(tag5).toInt();
    m_config.yAxisTickPoints = m_chartConfigFile.GetConfig(tag6).toInt();
    m_config.screenShotPath = m_chartConfigFile.GetConfig(tag7).toString();
}

void MainWindow::setConfig()
{
    QString tag1 = "Theme",tag2 = "OpenGl", tag3 = "Resolution", tag4 = "MaxTip", tag5 = "MaxXaxis", tag6 = "MaxYaxis", tag7 = "ScreenShootPath";
    m_config = m_configDialog->configure();
    QVariant themeCode = int(m_config.chartTheme);
    m_chartConfigFile.setConfig(tag1,themeCode);
    QVariant openglCode = m_config.enableOpenGL;
    m_chartConfigFile.setConfig(tag2,openglCode);
    QVariant resCode = m_config.displayResolution;
    m_chartConfigFile.setConfig(tag3, resCode);
    QVariant maxTipCode = m_config.maxTipPoints;
    m_chartConfigFile.setConfig(tag4, maxTipCode);
    QVariant xCode = m_config.xAixsTickPoints;
    m_chartConfigFile.setConfig(tag5, xCode);
    QVariant yCode = m_config.yAxisTickPoints;
    m_chartConfigFile.setConfig(tag6, yCode);
    QVariant path = m_config.screenShotPath;
    m_chartConfigFile.setConfig(tag7, path);


}

void MainWindow::screenShot()
{
    if(m_myChart != 0 && m_seriesData.count()>0)
    {
        QScreen *shotScreen = QGuiApplication::primaryScreen();
        QPixmap p = shotScreen->grabWindow(m_myChart->winId());
        QImage image = p.toImage();
        auto id = QUuid::createUuid().toString();
        qDebug()<<"id is "<<id;
        QString filePath = m_config.screenShotPath + "/" + m_originFileName + "_" + id + ".png";
        qDebug()<<filePath;
        image.save(filePath);
        qDebug()<<"screen shot successful!";
        QSound *shootSound = new QSound(":/Sound/screenShot");
        shootSound->play();

    }else {

        QMessageBox::warning(this,tr("截屏失败"),tr("请检查曲线文件!"));
    }

}

void MainWindow::receiveConfigure()
{

    setConfig();
}

void MainWindow::on_action_remove_triggered()
{
    if(!m_seriesData.empty())
    {
        m_myChart->removeSeries();
        m_myChart->removeTips();
        m_seriesData.clear();
    }



}

void MainWindow::on_action_exit_triggered()
{
    qApp->quit();
}

void MainWindow::on_action_config_triggered()
{

    m_configDialog->setConfigure(m_config);
    m_configDialog->show();
}

void MainWindow::on_action_screeshot_triggered()
{
    screenShot();
}

void MainWindow::on_action_info_triggered()
{
    m_infoDialog->show();
}
